package com.sskj.hhrt;

import android.app.Activity;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog.Builder;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import sskj.lee.appupdatelibrary.BaseVersion;
import sskj.lee.appupdatelibrary.R.style;

import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;

public abstract class BaseUpdateDialogFragment extends DialogFragment {
    private Activity mActivity;
    public BaseVersion mVersionData;
    private int PERMISSION_REQUEST_WRITE_SD = 1024;
    public static String INTENT_KEY = "result_key";
    private DownloadTask mDownloadTask;

    public BaseUpdateDialogFragment() {
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setCancelable(false);
        this.setStyle(1, style.Theme_Design_BottomSheetDialog_NoActionBar);
    }

    @Nullable
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View inflate = LayoutInflater.from(this.getActivity()).inflate(this.getLayoutId(), (ViewGroup) null);
        this.mActivity = this.getActivity();
        return inflate;
    }

    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        this.mVersionData = (BaseVersion) this.getArguments().getSerializable(INTENT_KEY);
        this.initView(view, this.mVersionData);
    }

    public void onDestroy() {
        super.onDestroy();
        if (this.mDownloadTask != null) {
            this.mDownloadTask.cancel(true);
        }

    }

    public abstract int getLayoutId();

    protected abstract void initView(View var1, BaseVersion var2);

    protected abstract void onDownLoadStart();

    protected abstract void onDownLoadUpdate(int var1);

    protected void onDownLoadFinish(File file) {
        if (file != null && file.exists()) {
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
            if (VERSION.SDK_INT >= 24) {
                Uri contentUri = FileProvider.getUriForFile(this.mActivity, this.mActivity.getPackageName() + ".fileProvider", file);
                intent.putExtra("output", contentUri);
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            } else {
                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
            }
            getActivity().startActivity(intent);
        }

    }

    void checkPermission() {
        if (ContextCompat.checkSelfPermission(mActivity, "android.permission.WRITE_EXTERNAL_STORAGE") != 0) {
            ActivityCompat.requestPermissions(mActivity, new String[]{"android.permission.WRITE_EXTERNAL_STORAGE"}, PERMISSION_REQUEST_WRITE_SD);
        } else if (!TextUtils.isEmpty(mVersionData.getUrl())) {
            if (mVersionData.isMustUp()) {
                openDownloadTask();
            } else if (mVersionData.getViewStyle() == 10010) {
                mActivity.startService((new Intent(mActivity, NotifyDownloadService.class)).putExtra(INTENT_KEY, mVersionData));
                dismiss();
            } else {
                openDownloadTask();
            }
        } else {
            Toast.makeText(getActivity(), "下载地址不能为空", 0).show();
        }

    }

    protected void openDownloadTask() {
        mDownloadTask = new DownloadTask();
        mDownloadTask.execute(new String[]{mVersionData.getUrl()});
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_WRITE_SD && grantResults[0] == 0) {
            startDownload();
        }

    }

    protected void startDownload() {
        checkPermission();
    }

    public void showMustUpDialog() {
        Builder builder = new Builder(mActivity);
        builder.setTitle("温馨提示").setMessage("本次更新是我们的一大步，放弃更新将会退出应用哦~!").setNegativeButton("关闭应用", new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                getActivity().finish();
            }
        }).setPositiveButton("继续更新", new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                checkPermission();
            }
        }).show();
    }

    public void showNotifyPermissionDialog() {
        Builder builder = new Builder(mActivity);
        builder.setTitle("温馨提示").setMessage("下载更新需要允许应用通知,是否打开应用通知").setNegativeButton("取消", new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).setPositiveButton("去打开", new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent intent = new Intent();
                if (VERSION.SDK_INT >= 26) {
                    intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
                    intent.putExtra("android.provider.extra.APP_PACKAGE", getActivity().getPackageName());
                } else if (VERSION.SDK_INT >= 21 && VERSION.SDK_INT < 26) {
                    intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
                    intent.putExtra("app_uid", getActivity().getApplicationInfo().uid);
                } else if (VERSION.SDK_INT < 21) {
                    intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                    intent.setData(Uri.fromParts("package", getActivity().getPackageName(), (String) null));
                }

                startActivity(intent);
            }
        }).show();
    }

    public class DownloadTask extends AsyncTask<String, Integer, File> {
        private boolean mCancelUpdata = false;

        public DownloadTask() {
        }

        protected void onPreExecute() {
            super.onPreExecute();
            onDownLoadStart();
        }

        protected File doInBackground(String... strings) {
            File apkFile = null;
            if (Environment.getExternalStorageState().equals("mounted")) {
                InputStream is = null;
                FileOutputStream fos = null;
                HttpURLConnection conn = null;

                try {
                    String savePath = String.format("%1$s/%2$s/download", Environment.getExternalStorageDirectory(), mActivity.getPackageName());
                    URL url = new URL(mVersionData.getUrl());
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestProperty("Accept-Encoding", "identity");
                    conn.connect();
                    long length = (long) conn.getContentLength();
                    File file = new File(savePath);
                    if (!file.exists()) {
                        file.mkdirs();
                    }

                    apkFile = new File(savePath, TextUtils.isEmpty(mVersionData.getVersionName()) ? String.valueOf(System.currentTimeMillis() + ".apk") : mVersionData.getVersionName() + ".apk");
                    if (apkFile.exists()) {
                        apkFile.delete();
                    }

                    is = conn.getInputStream();
                    fos = new FileOutputStream(apkFile);
                    long count = 0L;
                    byte[] buf = new byte[1024];

                    do {
                        int readNum = is.read(buf);
                        if (readNum <= 0) {
                            mCancelUpdata = true;
                            break;
                        }

                        count += (long) readNum;
                        fos.write(buf, 0, readNum);
                        publishProgress(new Integer[]{(int) (count * 100L / length)});
                    } while (!mCancelUpdata);

                    fos.close();
                    is.close();
                } catch (MalformedURLException var25) {
                    var25.printStackTrace();
                } catch (IOException var26) {
                    var26.printStackTrace();
                } finally {
                    try {
                        if (fos != null) {
                            fos.close();
                        }

                        if (is != null) {
                            is.close();
                        }
                    } catch (IOException var24) {
                    }

                    if (conn != null) {
                        conn.disconnect();
                    }

                }
            } else {
                Toast.makeText(mActivity, "未检测到SD卡", 0).show();
            }

            return apkFile;
        }

        protected void onProgressUpdate(Integer... values) {
            onDownLoadUpdate(values[0]);
        }

        protected void onCancelled() {
            super.onCancelled();
        }

        protected void onPostExecute(File file) {
            super.onPostExecute(file);
            dismiss();
            onDownLoadFinish(file);
            mDownloadTask.cancel(true);
        }
    }
}
